package com.rtx.express.service.impl;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.rtx.common.Base64Helper;
import com.rtx.common.MD5Helper;
import com.rtx.edi.model.express.bo.ExpressBO;
import com.rtx.edi.model.express.po.PlExpressApi;
import com.rtx.edi.model.express.po.PlExpressApiConfig;
import com.rtx.edi.model.express.po.PlExpressResult;
import com.rtx.express.service.IExpressService;

import cn.hutool.http.HttpRequest;

@Service("快递接口ST")
public class StoExpressAPI implements IExpressService{
	
	Logger log = LoggerFactory.getLogger(this.getClass());

	private static String create_order_url="https://cloudinter-linkgatewayonline.sto.cn/gateway/link.do";
	private static String appkey ="CAKKhDkhyGlDaWR";
	private static String secretkey ="ProFI7FYtFml8mhiPAAunqhYJNejvCFm";
	private static String sitcode ="215410";
	private static String customerName ="浮桥春风物流";
	private static String code ="CAKKhDkhyGlDaWR";
	private static String sitpwd ="147258";
	
	@Override
	public void callCreaterOrderAPI(ExpressBO bo) {
		PlExpressApi task =  bo.getExpressTask();
		PlExpressApiConfig config = bo.getExpressConfig();
		try {
			String requestStr = coverToSTORequest(bo);
			
			String digest = calculateDigest(requestStr,secretkey);
			
			Map<String,Object> reqmap  = new HashMap<>();
			
			reqmap.put("api_name", "OMS_EXPRESS_ORDER_CREATE");//调用的目标接口ID（控制台列表中称为API，为英文、数字及下划线组成的字串，非API中文名称）
			reqmap.put("content", requestStr);//结构化的业务报文体，具体内容由订阅的接口规定（API文档中的 请求参数 表格）
			reqmap.put("from_appkey", appkey);//订阅方appkey，即合作方应用key
			reqmap.put("from_code", code);//订阅方资源code，即合作方应用的资源code
			reqmap.put("to_appkey", "sto_oms");//注册方appkey，即提供该订阅接口服务的申通应用key
			reqmap.put("to_code", "sto_oms");//注册方资源code，即上述申通应用的资源code，目前值等于to_appkey
			reqmap.put("data_digest", digest);
			
			
			log.info("订单-{}-获取申通快递请求：{}",task.getExternorderkey(),requestStr);
			//发送请求
			String responseStr = HttpRequest
					.post(create_order_url)
					.form(reqmap)
					.timeout(30000)
					.execute()
					.body();
			log.info("订单-{}-获取申通快递请求响应：{}",task.getExternorderkey(),responseStr);
			
			JSONObject jsonresult = JSONObject.parseObject(responseStr);
			if("true".equals(jsonresult.get("success").toString())){
				bo.setCallCreateOrderAPIResult("ok");
				bo.setCallCreateOrderAPIData(responseStr);
				
				PlExpressResult result = bo.getExpressResultFillSendAndReceiver();
				result.setExternorderkey(task.getExternorderkey());
				JSONObject stoRes = JSON.parseObject(bo.getCallCreateOrderAPIData()).getJSONObject("data");
				result.setWaybillNo(stoRes.getString("waybillNo"));
				result.setZtobigWord(stoRes.getString("bigWord"));
				result.setZtopackagePlace(stoRes.getString("packagePlace"));
				bo.setExpressResult(result);
			}else {
				bo.setCallCreateOrderAPIData(responseStr);
			}
		} catch (Exception e) {
			log.info("订单-{}-获取申通快递单号失败-{}",task.getExternorderkey(),e);
		}
	}
	
	private String coverToSTORequest(ExpressBO bo) {
		PlExpressApi task =  bo.getExpressTask();
		PlExpressApiConfig config = bo.getExpressConfig();
		//带*必填动态数据
		JSONObject jsonboby = new JSONObject();
		if(bo.getZdflag() == true) {
			jsonboby.put("orderNo",task.getExternorderkey()+System.currentTimeMillis());
		}else {
			jsonboby.put("orderNo",task.getExternorderkey());
		}
		jsonboby.put("orderNo",task.getExternorderkey());
		jsonboby.put("orderSource", "VIPEO");
		jsonboby.put("billType", "00");
		jsonboby.put("orderType", "01");
		
		JSONObject jsonsender = new JSONObject();
		
		jsonsender.put("name", task.getSendAddress());
		jsonsender.put("tel", task.getSendPhone());
		jsonsender.put("mobile", task.getSendMobile());
		jsonsender.put("postCode", "");
		jsonsender.put("country", "中国");
		jsonsender.put("province", task.getSendProvince());
		jsonsender.put("city", task.getSendCity());
		jsonsender.put("area", task.getSendProvince()+task.getSendCity()+task.getSendCounty());
		jsonsender.put("town", task.getSendCounty());
		jsonsender.put("address", task.getSendAddress());
		
		jsonboby.put("sender", jsonsender);
		
		//出库单相关信息
		
		JSONObject jsonrecver = new JSONObject();	
		jsonrecver.put("name", task.getReceiverName());
		jsonrecver.put("tel", task.getReceiverPhone());
		jsonrecver.put("mobile", task.getReceiverMobile());
		jsonrecver.put("postCode", "");
		jsonrecver.put("country", "中国");
		jsonrecver.put("province", task.getReceiverProvince());
		jsonrecver.put("city", task.getReceiverCity());
		jsonrecver.put("area",task.getReceiverCounty());
		jsonrecver.put("town", "");
		jsonrecver.put("address", task.getReceiverAddress());
		
		jsonboby.put("receiver", jsonrecver);
		
		JSONObject jsoncargo = new JSONObject();
		jsoncargo.put("battery","10");
		jsoncargo.put("goodsType","小件");
		jsoncargo.put("goodsName","食品");
		
		jsonboby.put("cargo", jsoncargo);
		
		JSONObject jsoncust = new JSONObject();
		jsoncust.put("siteCode", sitcode);
		jsoncust.put("customerName",customerName);
		jsoncust.put("sitePwd", sitpwd);
		
		jsonboby.put("customer", jsoncust);
		return jsonboby.toJSONString();
	}

	
	/**
	 * 计算签名值
	 *
	 * @param content  请求报文体
	 * @param secretkey   from_appkey 配置的私钥
	 * @return
	 */
	public static String calculateDigest(String content, String secretKey) {
	    String text = content + secretKey;
	    byte[] md5 = MD5Helper.encryptMD5(text, "utf-8");
	    return Base64Helper.encode(md5);
	}
	
	public static String buildMap(Map<String, String> map) {
        StringBuffer sb = new StringBuffer();
        if (map.size() > 0) {
            for (String key : map.keySet()) {
                sb.append(key + "=");
                if (StringUtils.hasText(map.get(key))) {
                    sb.append("&");
                } else {
                    String value = map.get(key);
                    try {
                        value = URLEncoder.encode(value, "UTF-8");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    sb.append(value + "&");
                }
            }
        }
        return sb.toString();
    }

	@Override
	public void handleCreaterOrderAPIResponse(ExpressBO bo) {}
}
